//
//  AppDelegate.m
//  SXH
//
//  Created by 房 国生 on 15/6/23.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "AppDelegate.h"
#import "CommonService.h"
#import "AdViewController.h"

#import "XGPush.h"
#import "XGSetting.h"
#import <AlipaySDK/AlipaySDK.h>
#import "OrderViewController.h"
#import "MobClick.h"
#import "WXPay.h"
#import "EnterShareViewController.h"
#import "OpenUDID.h"
#define FTAPPKEY  @"5600fb28e0f55adb9100072f"
@interface AppDelegate ()
@property (nonatomic,strong) BaseViewController *baseVC;
@end

BMKMapManager* _mapManager;
@implementation AppDelegate
@synthesize file_from_local,spot_from_local;
@synthesize pushToken;
@synthesize wrapperMainVC;
@synthesize statusCustomView;

+ (AppDelegate *)instance {
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (id)init {
    self = [super init];
    if (self) {
        _dpapi = [[DPAPI alloc] init];
        _appKey = [[NSUserDefaults standardUserDefaults] valueForKey:@"appkey"];
        if (_appKey.length<1) {
            _appKey = kDPAppKey;
        }
        _appSecret = [[NSUserDefaults standardUserDefaults] valueForKey:@"appsecret"];
        if (_appSecret.length<1) {
            _appSecret = kDPAppSecret;
        }
    }
    return self;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSLog(@"%@",NSHomeDirectory());
    NSLog(@"OpenUDID = %@",[OpenUDID value]);

    // Override point for customization after application launch.
    // 要使用百度地图，请先启动BaiduMapManager
    [self initXGPush:launchOptions];
    //
    NSString *cid = [[NSUserDefaults standardUserDefaults] valueForKey:SelectedCityId];
    NSString *cname = [[NSUserDefaults standardUserDefaults] valueForKey:SelectedCityName];
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:SelectedCityDifferent];
    
    if (cid == nil) {
        self.dicCurrentCity = [[NSDictionary alloc]initWithObjectsAndKeys:@"北京", @"cname",@"1", @"id", nil];
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:SelectedCurrentCity];
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:SelectedCityId];
        [[NSUserDefaults standardUserDefaults] setObject:@"北京" forKey:SelectedCityName];
        
    } else {
        self.dicCurrentCity = [[NSDictionary alloc]initWithObjectsAndKeys:cname, @"cname",cid, @"id", nil];
    }
    
    NSString *path=[[NSBundle mainBundle] pathForResource:@"citydict"
                                                   ofType:@"plist"];
    self.cities = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    
    file_from_local = NO;
    spot_from_local = NO;
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:BAIDU_MAP_KEY generalDelegate:self];
    
    if (!ret) {
        DebugLog(@"manager start failed!");
    } else {
        DebugLog(@"manager start success!");
    }
    [self loadUserEntityFromArchiver];
    //[self setNavTintColorAndFont];
    [CommonService initShareSDK];
    
    UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window = window;
    [self.window changeRootViewController:nil];
    
    [self.window makeKeyAndVisible];
    
    [MobClick startWithAppkey:FTAPPKEY reportPolicy:BATCH channelId:@"www.baidu.com"];
    [MobClick setCrashReportEnabled:NO];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (!_alreadyLunch) {
        return;
    }
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSString *coppedString = [[UIPasteboard generalPasteboard] valueForPasteboardType:[UIPasteboardTypeListString objectAtIndex:0] ];
    UserEntity *userEntity = [UserEntity sharedInstance];
    //判断是不是自己发的
    if (userEntity.login == YES) {
        if ([coppedString containsString:userEntity.nickName]) {
            return;
        }
    }
    if ([coppedString containsString:@"#乐游口令#"]) {
        NSRange range =  [coppedString rangeOfString:@"进群口令"];
        NSRange range2 = [coppedString rangeOfString:@"】"];
        NSRange range3 = NSMakeRange((range.location +range.length), (range2.location - range.location -range.length));
        NSString * room_id = [coppedString substringWithRange:range3];
        [[UIPasteboard generalPasteboard] setValue:@"" forPasteboardType:[UIPasteboardTypeListString objectAtIndex:0]];
        EnterShareViewController *vc = [[EnterShareViewController alloc] init];
        UINavigationController *nav =[[UINavigationController alloc] initWithRootViewController:vc];
        vc.room_id = room_id;
        UIViewController *vc2 = [UIApplication sharedApplication].keyWindow.rootViewController;
        vc.navigationController.navigationBar.hidden = YES;
        [vc2 presentViewController:nav animated:YES completion:^{
            ;
        }];
    }

   
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)setAppKey:(NSString *)appKey {
    _appKey = appKey;
    [[NSUserDefaults standardUserDefaults] setValue:appKey forKey:@"appkey"];
}

- (void)setAppSecret:(NSString *)appSecret {
    _appSecret = appSecret;
    [[NSUserDefaults standardUserDefaults] setValue:appSecret forKey:@"appsecret"];
}

- (void)setNavTintColorAndFont {
    UIBarButtonItem *barItemInNavigationBarAppearanceProxy = [UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil];
    
    //设置字体为加粗的12号系统字，自己也可以随便设置。
    [barItemInNavigationBarAppearanceProxy setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14], NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
    
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName]];
    
}

- (void)onGetNetworkState:(int)iError {
    if (0 == iError) {
        NSLog(@"联网成功");
    } else{
        NSLog(@"onGetNetworkState %d",iError);
    }
}

- (void)onGetPermissionState:(int)iError {
    if (0 == iError) {
        NSLog(@"授权成功");
    } else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}

//- (void)locationUpdated {
//    LocationManagement *lm = [LocationManagement sharedInstance];
//    [lm performCoordinateGeocode:lm.location.coordinate
//                         success:^(id responseObject) {
//                             NSDictionary *placeCityDic = (NSDictionary *)responseObject;
//                             lm.city = [placeCityDic objectForKey:@"City"];
//                             
//                             [[NSUserDefaults standardUserDefaults] setObject:lm.city forKey:@"city"];
//                             [[NSUserDefaults standardUserDefaults] synchronize];
//                             
//                         } failure:^(NSError *error) {
//                         }];
//    DebugLog(@"locationUpdated = %@, %f, %f", lm.city, lm.location.coordinate.latitude, lm.location.coordinate.longitude);
//    [lm stopGPS];
//}

//- (void)locationUpdatedFailed:(int)errorCode ErrorMessage:(NSString *)message {
//}

- (void) loadUserEntityFromArchiver {
    NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:@"UserEntity"];
    if (userData != nil) {
        UserEntity *userEntity = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
        
        if (userEntity != nil) {
            [[UserEntity sharedInstance] deepCopy:userEntity];
        }
    }
}

- (void) saveUserEntity:(UserEntity *) userEntity {
    //本地保存用户信息
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:userEntity];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:myEncodedObject forKey:@"UserEntity"];
    [defaults synchronize]; 
}

- (void) removeUserEntity {
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"UserEntity"];
    [defaults synchronize];
}

//--------------------------------------------------信鸽推送-------------------------------------------------------------
- (void) initXGPush:(NSDictionary *)launchOptions {
    //[XGPush handleReceiveNotification:nil];
    
    //初始化app
    //[XGPush startWithAppkey:@"IN421FX97FUT"];
    
    //[XGPush startAppForMSDK:354 appKey:@"xg354key"];
    //[XGPush startApp:101 appKey:@"akey"];
    
    [XGPush startApp:XINGE_APP_ID appKey:XINGE_APP_KEY];
    //[XGPush startApp:2290000353 appKey:@"key1"];
    
    //注销之后需要再次注册前的准备
    void (^successCallback)(void) = ^(void){
        //如果变成需要注册状态
        if(![XGPush isUnRegisterStatus])
        {
            //iOS8注册push方法
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
            
            float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
            if(sysVer < 8){
                [self registerPush];
            }
            else{
                [self registerPushForIOS8];
            }
#else
            //iOS8之前注册push方法
            //注册Push服务，注册后才能收到推送
            [self registerPush];
#endif
        }
    };
    [XGPush initForReregister:successCallback];
    
    //[XGPush registerPush];  //注册Push服务，注册后才能收到推送
    
    //推送反馈(app不在前台运行时，点击推送激活时)
    [XGPush handleLaunching:launchOptions];
    
    //推送反馈回调版本示例
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush]handleLaunching's successBlock");
    };
    
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush]handleLaunching's errorBlock");
    };
    
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    //清除所有通知(包含本地通知)
    //[[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    [XGPush handleLaunching:launchOptions successCallback:successBlock errorCallback:errorBlock];
    
    //本地推送示例
    /*
     NSDate *fireDate = [[NSDate new] dateByAddingTimeInterval:10];
     
     NSMutableDictionary *dicUserInfo = [[NSMutableDictionary alloc] init];
     [dicUserInfo setValue:@"myid" forKey:@"clockID"];
     NSDictionary *userInfo = dicUserInfo;
     
     [XGPush localNotification:fireDate alertBody:@"测试本地推送" badge:2 alertAction:@"确定" userInfo:userInfo];
    */
    // Override point for customization after application launch.
}

- (void)registerPushForIOS8 {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    
    //Types
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    
    //Actions
    UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
    
    acceptAction.identifier = @"ACCEPT_IDENTIFIER";
    acceptAction.title = @"Accept";
    
    acceptAction.activationMode = UIUserNotificationActivationModeForeground;
    acceptAction.destructive = NO;
    acceptAction.authenticationRequired = NO;
    
    //Categories
    UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
    
    inviteCategory.identifier = @"INVITE_CATEGORY";
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextDefault];
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextMinimal];
    
    NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
    
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
    
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}

- (void)registerPush {
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}


-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    //notification是发送推送时传入的字典信息
    [XGPush localNotificationAtFrontEnd:notification userInfoKey:@"clockID" userInfoValue:@"myid"];
    
    //删除推送列表中的这一条
    [XGPush delLocalNotification:notification];
    //[XGPush delLocalNotification:@"clockID" userInfoValue:@"myid"];
    
    //清空推送列表
    //[XGPush clearLocalNotifications];
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_

//注册UserNotification成功的回调
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //用户已经允许接收以下类型的推送
    //UIUserNotificationType allowedTypes = [notificationSettings types];
    
}

//按钮点击事件回调
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler{
    if([identifier isEqualToString:@"ACCEPT_IDENTIFIER"]){
        NSLog(@"ACCEPT_IDENTIFIER is clicked");
    }
    
    completionHandler();
}

#endif

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    //NSString * deviceTokenStr = [XGPush registerDevice:deviceToken];
    
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush]register successBlock");
    };
    
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush]register errorBlock");
    };
    
    //注册设备
    [[XGSetting getInstance] setChannel:@"appstore"];
    [[XGSetting getInstance] setGameServer:@"巨神峰"];
    
    
    pushToken = [XGPush registerDevice:deviceToken successCallback:successBlock errorCallback:errorBlock];
    
    //如果不需要回调
    [XGPush registerDevice:deviceToken];
    
    //打印获取的deviceToken的字符串
    NSLog(@"deviceTokenStr is %@",pushToken);
}

//如果deviceToken获取不到会进入此事件
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSString *str = [NSString stringWithFormat: @"Error: %@",err];
    NSLog(@"%@",str);
}

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo {
    //推送反馈(app运行时)
    [XGPush handleReceiveNotification:userInfo];
    //回调版本示例
     void (^successBlock)(void) = ^(void){
         //成功之后的处理
         if (_mainVC != nil) {
             [_mainVC handleNotification:userInfo];
         }
         NSLog(@"[XGPush]handleReceiveNotification successBlock");
     };
     
     void (^errorBlock)(void) = ^(void){
         //失败之后的处理
         NSLog(@"[XGPush]handleReceiveNotification errorBlock");
     };
     
     void (^completion)(void) = ^(void){
         //失败之后的处理
         NSLog(@"[xg push completion]userInfo is %@",userInfo);
     };
     
     [XGPush handleReceiveNotification:userInfo successCallback:successBlock errorCallback:errorBlock completion:completion];
}

//--------------------------------------------------------------------------------------------------------------------
//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
//{
//    WXPay *wxpay=[[WXPay alloc]init];
//    return  [WXApi handleOpenURL:url delegate:wxpay];
//}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    NSString *string =[url absoluteString];
    if([string hasPrefix:@"alipayByLeyou"]){
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic){
            NSLog(@"result = %@",resultDic);
            UserEntity *userEntity = [UserEntity sharedInstance];
            OrderViewController *vc=[[OrderViewController alloc]init];
            vc.userId=userEntity.userId;
            if([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"6001"]){
                ALERT_ERR_MSG(PayCanceled);
                vc.orderFlag=NO;
            }
            if([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]){
                ALERT_ERR_MSG(PaySuccess);
                vc.orderFlag=YES;
            }
            
            if (self.mainVC != nil) {
                [self.mainVC.navigationController pushViewController:vc animated:YES];
            } else {
                [self.wrapperMainVC.navigationController pushViewController:vc animated:YES];
            }
        }];
    }else if ([string hasPrefix:@"wxe8f31d9530798638"]){
        WXPay *wxpay=[[WXPay alloc]init];
        return  [WXApi handleOpenURL:url delegate:wxpay];
    }
    
    return YES;
}

//***********************************************************************************************************************

- (void) showCustomView:(BOOL)show {
    if (statusCustomView == nil) {
        statusCustomView = [[UIViewController alloc] init ];
            statusCustomView.view.frame = CGRectMake(0, 0, SCREEN_HEIGHT, 20);
    }
    
    if (show == YES) {
        statusCustomView.view.backgroundColor = [UIColor blueColor];
        [[AppDelegate instance].window addSubview:statusCustomView.view];
        UITapGestureRecognizer *click = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showControl) ];
        [statusCustomView.view addGestureRecognizer:click];
        statusCustomView.view.userInteractionEnabled = YES;
    } else {
        [statusCustomView.view removeFromSuperview];
        statusCustomView = nil;
    }
}

-(void)showControl
{
}

@end


